<?php

namespace App\Http\Middleware;

use App\Models\Rbac\Role;
use App\Models\Rbac\UserRole;
use App\Rep\Rbac\RoleRep;
use App\Rep\Rbac\UserRep;
use Closure;
use Illuminate\Http\Request;

class CheckLoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $token = $request->header("token")??$request->get('token');
        if(empty($token)){
            return re(1003);
        }else{
            $user_info = UserRep::getUserInfoForToken($token);
            if(empty($user_info)){
                return re(5001);
            }else{
                UserRep::resetUserTokenExpire($token);
                $request->offsetSet("user_info",$user_info);
                $request->offsetSet("username",$user_info['username']);
                $request->offsetSet("user_id",$user_info["id"]);
                $request->offsetSet("token",$token);
                $role_id = UserRole::where('user_id',$user_info['id'])->value('role_id');
                $role = Role::where('id',$role_id)->first();
                if($role->status == 2){
                    return re(1009);
                }
                $request->offsetSet("role_id",$role_id);
                $request->offsetSet("role_name",$role->name);
                $RoleRep = new RoleRep();
                $permissions = $RoleRep->getButtonRoute($role_id);
                $request->offsetSet("permissions",$permissions);

            }
        }

        return $next($request);
    }
}
